package servlet;

import it.polimi.swimv2.entities.Feedback;
import it.polimi.swimv2.entities.User;
import it.polimi.swimv2.exception.UserNotFoundException;
import it.polimi.swimv2.remote.UserProfileManagerRemote;
import it.polimi.swimv2.util.RemoteBindingName;

import java.io.IOException;
import java.util.Collection;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class UserProfileServlet
 */
public class UserProfileServlet extends HttpServlet {

	
	private static final String SESSION_USERNAME = "user";
	//Page references:
	private static final String USER_PROFILE_JSP = "userProfile.jsp";
	private static final String LOGIN_FORM_JSP = "loginForm.jsp";
	private static final String INDEX_JSP = "index.jsp";
	private static final String ERROR_JSP = "error.jsp";
	//Actions performed by this Servlet:
	private static final String ACT_PARAMETER = "act";
	private static final String SHOW_USER_PROFILE_ACT="showUserProfile";
	//Parameters in HttpRequest:
	private static final String FEEDBACKS_REQPARAM = "feedbacks";//Collection<Feedback>
	private static final String USER_REQPARAM = "user";//User
	private static final String USERNAME_PARAM="username";//String
	private static final String EXISTS_FR_REQUEST_REQPARAM = "existsFrRequest";//boolean
	private static final String IS_FRIEND_REQPARAM = "isFriend";//boolean
	
	private static final long serialVersionUID = 1L;
	
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserProfileServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		chooseAction(request, response);
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		chooseAction(request, response);
	}
	/**
	 * manages the action requested by http request
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void chooseAction(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		
		HttpSession session = request.getSession();
		String sessionUsername = (String) session.getAttribute(SESSION_USERNAME);
		String actParam = request.getParameter(ACT_PARAMETER);
		if (sessionUsername == null) {
			response.sendRedirect(LOGIN_FORM_JSP);
			return;
		}
		if(actParam==null){
			response.sendRedirect(ERROR_JSP);
			return;
		}
		
		if(actParam.equals(SHOW_USER_PROFILE_ACT)){
			showUserProfile(request,response);
		}else{
			response.sendRedirect(INDEX_JSP);
		}
	}
	/**
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void showUserProfile(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		
		String username = request.getParameter(USERNAME_PARAM);
		HttpSession session = request.getSession();
		String sessionUsername = (String) session.getAttribute(SESSION_USERNAME);
	
		if(sessionUsername.equals(username)){
			fowardToPersonalProfile(request, response);
			return;
		}
		try {
			UserProfileManagerRemote rem=retrieveUserProfileManagerRemote();
			User user=rem.getUserDetail(username);
			if (user==null){
				response.sendRedirect(ERROR_JSP);
				return;
			}
			
			boolean isFriend=rem.areFriend(sessionUsername, username);
			boolean existsFrRequest=rem.existFriendshipRequest(sessionUsername, username);
			Collection<Feedback> feedbacks=rem.getFeedbackOf(username);
			setBlankValue(user);
			request.setAttribute(USER_REQPARAM, user);
			request.setAttribute(FEEDBACKS_REQPARAM, feedbacks);
			request.setAttribute(IS_FRIEND_REQPARAM, isFriend);
			request.setAttribute(EXISTS_FR_REQUEST_REQPARAM, existsFrRequest);
			RequestDispatcher dispatcher = request.getRequestDispatcher(USER_PROFILE_JSP);
			dispatcher.forward(request, response); 
			return;
			
		} catch (NamingException e) {
			response.sendRedirect(ERROR_JSP);			
		} catch (UserNotFoundException e) {
			response.sendRedirect(ERROR_JSP);	
		}
		
	}
	/**
	 * redirect the action to UserServlet in order to show own profile
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void fowardToPersonalProfile(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String url = "UserServlet?act=showPersonalProfile";
		RequestDispatcher dispatcher = request.getRequestDispatcher(url);
		dispatcher.forward(request, response);
	}
	/**
	 * 
	 * @param user
	 */
	private void setBlankValue(User user) {
		if(user.getCity().equals("")){
			user.setCity("-");
		}
		if(user.getPhone().equals("")){
			user.setPhone("-");
		}		
	}
	/**
	 * retrieves the remote object
	 * @return
	 * @throws NamingException
	 */
	private UserProfileManagerRemote retrieveUserProfileManagerRemote()
			throws NamingException {
		Context jndiContext = new InitialContext();
		Object ref = jndiContext.lookup(RemoteBindingName.USER_PROFILE_MANAGER);
		UserProfileManagerRemote rem = (UserProfileManagerRemote) ref;
		return rem;
	}

}
